package vrbm

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"vrcm/src/vrcm/app/admin/models"
	dto "vrcm/src/vrcm/app/admin/service/dto/vrbm"
	"vrcm/src/vrcm/common/service"
	ext "vrcm/src/vrcm/envconfig"
)

var client = http.Client{}

type VrbmService struct {
	service.Service
}

func (e *VrbmService) GetOnTimeList(d *dto.OnTimeListReq) ([]dto.OnTimeListRes, error) {

	res := make([]dto.OnTimeListRes, 0, 5)
	urlPath := ext.ExtConfig.ServiceConfig.VrbmServiceUrl + "/v1/order/user/onTimeList"
	e.Log.Trace("GetOnTimeList path:", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["tenant_id"] = d.TenantId
	data["related_product"] = d.RelatedProduct
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return res, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("GetOnTimeList:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &res)
	if err != nil {
		e.Log.Errorf("反序列化失败:%s", err)
		return res, err
	}
	return res, nil
}
